# coding=utf8

import os

class Preliminary:

    @staticmethod
    def demo_bytes_data():
        b1 = b'123'
        b2 = b'\x21\xF5'
        print(b1, b2)

        bs1 = '中文'.encode('utf8')
        bs2 = '中文'.encode('utf16')
        print(bs1, bs2)

    @staticmethod
    def demo_bin_file():
        base_dir = os.path.dirname(os.path.abspath(__file__))

        # 写字节数据到二进制文件
        bin_file = os.path.join(base_dir, 'file42exp1.bin')
        fobj = open(bin_file, 'wb')
        fobj.write(b'123456789')
        fobj.close()

        # 读取二进制文件数据
        bin_file = os.path.join(base_dir, 'file42exp1.bin')
        fobj = open(bin_file, 'rb')
        rb = fobj.read(6)
        fobj.close()
        print(rb)

        # 写字节数据到二进制文件
        bin_file = os.path.join(base_dir, 'file42exp2.bin')
        fobj = open(bin_file, 'wb')
        fobj.write('我们的祖国'.encode())
        fobj.close()

        # 读取二进制文件数据
        bin_file = os.path.join(base_dir, 'file42exp2.bin')
        with open(bin_file, 'rb') as fobj:
            rb = fobj.read(6)
            fobj.close()
            print(rb.decode())


def task():
    base_dir = os.path.dirname(os.path.abspath(__file__))

    # 写字节数据到二进制文件
    bin_file = os.path.join(base_dir, 'file42.bin')
    bin_data1 = "中国是一个古老的国家，幅员辽阔，美丽富饶。".encode('utf8')
    with open(bin_file, 'wb') as fobj:
        fobj.write(bin_data1)

    # 添加二进制数据到二进制文件
    bin_data2 = '面积为960万平方公里。'.encode('utf8')
    with open(bin_file, 'ab') as fobj:
        rb = fobj.write(bin_data2)

    # 读取二进制文件
    with open(bin_file, 'rb') as fobj:
        print(fobj.read().decode('utf8'))


def expand_1():
    base_dir = os.path.dirname(os.path.abspath(__file__))

    # 写字节数据到二进制文件
    bin_file = os.path.join(base_dir, 'file42expand1.bin')
    bin_data1 = "中国是一个古老的国家，幅员辽阔，美丽富饶。".encode('gbk')
    with open(bin_file, 'wb') as fobj:
        fobj.write(bin_data1)

    # 添加二进制数据到二进制文件
    bin_data2 = '面积为960万平方公里。'.encode('gbk')
    with open(bin_file, 'ab') as fobj:
        rb = fobj.write(bin_data2)

    # 读取二进制文件
    with open(bin_file, 'rb') as fobj:
        print(fobj.read().decode('gbk'))


if __name__ == '__main__':
    # Preliminary.demo_bytes()
    # Preliminary.demo_bin_file()
    # task()
    expand_1()

